﻿#include "TitleDirectory.h"
#include"XStringOperation.hpp"
#include"XQMouseEventFilter_Press.hpp"
#include<QMouseEvent>
#include<QStandardItemModel>
#include<QTableView>
#include<QMap>
#include<QMenu>
#include<QStack>
TitleDirectory::TitleDirectory(QWidget* parent)
	:QTreeView(parent),
	m_model(new QStandardItemModel(this))
{
	this->setModel(m_model);
	m_model->setHorizontalHeaderItem(0, new QStandardItem("标题"));
	setAnimated(true);//展开或折叠时动画显示
	//setRootIsDecorated(false);
	setDragEnabled(false);//禁止拖拽
	setEditTriggers(QTableView::EditTrigger::NoEditTriggers);	//禁止编辑

	init_Menu();
}

TitleDirectory::~TitleDirectory()
{
	if (m_model != nullptr)
		delete m_model;
	if (m_menu != nullptr)
		delete m_menu;
}

QStandardItem* TitleDirectory::itemFromIndex(const QModelIndex& index) const
{
	return m_model->itemFromIndex(index);
}

void TitleDirectory::setExpand(const bool expand)
{
	m_expand = expand;
	expandAll();//展开
}

void TitleDirectory::init_Menu()
{
	m_menu=new QMenu(this) ;
	m_menu->addAction("全部展开", [=]() {this->expandAll(); });
	m_menu->addAction("全部折叠", [=]() {this->collapseAll(); });
	m_menu->addSeparator();
	m_menu->addAction("大纲视图(可折叠)", [=]() {this->setItemsExpandable(true); });
	m_menu->addAction("大纲视图(无折叠)", [=]() {this->setItemsExpandable(false); expandAll(); });
	//installEventFilter(new XQMouseEventFilter_Press([=](QMouseEvent* ev)->bool {
	//	qInfo() << "鼠标按下";
	//	if (ev->button() == Qt::MouseButton::RightButton)//右键按下
	//	{
	//		qInfo() << "鼠标右键按下";
	//		m_menu->exec(QCursor::pos());//弹出菜单
	//		return true;
	//	}
	//return false;
	//	}));
}

void TitleDirectory::mousePressEvent(QMouseEvent* ev)
{
	if (ev->button() == Qt::MouseButton::RightButton)//右键按下
	{
		//qInfo() << "鼠标右键按下";
		m_menu->exec(QCursor::pos());//弹出菜单
	}
	QTreeView::mousePressEvent(ev);
}

void TitleDirectory::setDirectory(const QString& Text)
{
	m_model->clear();
	m_model->setHorizontalHeaderItem(0, new QStandardItem("标题"));
	QStringList strList;//保存从文本中提取的标题
	XStringOperation::regex_extract("(^#+ .+?)\n", Text, strList);
	QStack<std::pair<QStandardItem*,size_t>> stack;//用来保存父节点以其等级
	QMap<QString,int> map;//记录出现了几次
	for (auto&data:strList)
	{
		map[data]++;
		auto temp = XStringOperation::strtok(data, " ");
		size_t Lv = temp[0].size();//等级
		QString name = temp[1];//名字
		auto item = new QStandardItem(name);
		QList<QVariant>list = { map[data] ,data };//携带出现次数和源码标题
		item->setData(list);
		while (!stack.isEmpty())
		{
			auto& pair = stack.top();
			if (Lv > pair.second)
			{
				pair.first->appendRow(item);
				stack.push(std::pair<QStandardItem*, size_t>(item, Lv));
				break;
			}
			else
			{
				stack.pop();
			}
		}
		if (stack.isEmpty())//没有父节点的时候
		{
			m_model->appendRow(item);
			stack.push(std::pair<QStandardItem*, size_t>(item, Lv));
		}
	}
	if (m_expand)//设置是否展开
		expandAll();//展开
	//qInfo() << strList;
}
